package com.springmvc.dao;

import com.springmvc.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public User getUser(User user) {
        String sql = "SELECT id,userName,password FROM t_user where userName=? and password=?";
        try{
            return jdbcTemplate.queryForObject(sql,
                    new BeanPropertyRowMapper<User>(User.class), user.getUserName(),user.getPassword());
        }catch (Exception e){
            return null;
        }
    }

    public Boolean save(User user) {
        String sql = "INSERT into t_user (userName,password) VALUES(?,?);";
        int update = jdbcTemplate.update(sql, user.getUserName(), user.getPassword());
        return update == 1;
    }

    public List<User> page(Integer current,Integer pageSize,String userName){
        /**
         * 当前页码:从1开始
         * MySQL的limit分页是从0开始
         * limit m,n:m是从第m条开始 和当前页码有一个转换 (current-1) * pageSize
         */
        Integer start = (current - 1) * pageSize;
        String sql = "select id,userName,password from t_user  limit ?,?";

        if(userName!=null && userName.trim().length()>0){
            sql = "select id,userName,password from t_user where userName like ? limit ?,?";
            userName = "%"+userName +"%";
            return jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class),userName,start,pageSize);
        }

        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class),start,pageSize);
    }

    public Integer count(){
        String sql = "select count(1) from t_user";
        return jdbcTemplate.queryForObject(sql, Integer.class);
    }

    public User getById(Long id) {
        try{
            String sql = "SELECT id,userName,password FROM t_user where id=?";
            return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class), id);
        }catch (Exception e){
            return null;
        }
    }

    public Boolean update(User user) {
        String sql = "update t_user set userName=?,password=? where id=?";
        int update = jdbcTemplate.update(sql, user.getUserName(), user.getPassword(),user.getId());
        return update == 1;
    }

    public void delById(Long id) {
        String sql = "delete from t_user where id = ?";
        int update = jdbcTemplate.update(sql, id);
    }
}
